<template>
  <div class="container">
    <div class="main">
      <div class="header">
        <el-button type="primary" @click="openDialog(null)">新建</el-button>
        <el-button type="success" @click="importData">导入</el-button>
        <el-button type="warning" @click="openEditDialog">展开/折叠</el-button>
        <el-select v-model="selectedFilter" placeholder="请选择状态">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
        <el-input placeholder="请输入关键字搜索" v-model="searchKeyword" />
        <el-button type="info" @click="query">查询</el-button>
        <el-button type="info" @click="resetSearch">重置</el-button>
      </div>

      <el-table :data="tableData" row-key="menu_id" border default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="menu_id" label="菜单ID" width="100" />
        <el-table-column prop="menu_name" label="菜单名称" />
        <el-table-column label="菜单图标" width="120">
          <template #default="{ row }">
            <el-icon>
              <component :is="row.menu_icon" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="menu_url" label="菜单路径" />
        <el-table-column label="菜单状态">
          <template #default="{ row }">
            {{ row.menu_state === 0 ? '停用' : row.menu_state === 1 ? '启用' : row.menu_state }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-space>
              <el-tooltip content="编辑" placement="top">
                <div class="operation-item" @click="openDialog(row)">
                  <el-icon class="operation-icon">
                    <Edit />
                  </el-icon>
                  <span>编辑</span>
                </div>
              </el-tooltip>
              <el-tooltip content="新增" placement="top">
                <div class="operation-item" @click="addSubMenu(row)">
                  <el-icon class="operation-icon">
                    <Plus />
                  </el-icon>
                  <span>新增</span>
                </div>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <div class="operation-item" @click="deleteMenu(row)">
                  <el-icon class="operation-icon delete">
                    <Delete />
                  </el-icon>
                  <span>删除</span>
                </div>
              </el-tooltip>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <!-- 新增/编辑对话框   -->
      <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
        <el-form :model="formData" label-width="120px">
          <el-form-item label="上级菜单">
            <el-input v-model="formData.menu_pid" readonly />
          </el-form-item>
          <el-form-item label="菜单图标">
            <el-input v-model="formData.menu_icon" />
          </el-form-item>
          <el-form-item label="菜单名称">
            <el-input v-model="formData.menu_name" />
          </el-form-item>
          <el-form-item label="菜单路径">
            <el-input v-model="formData.menu_url" />
          </el-form-item>
          <el-form-item label="菜单状态">
            <el-radio-group v-model="formData.menu_state">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Edit, Plus, Delete } from '@element-plus/icons-vue';

// 表格数据
const tableData = ref([]);
// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formData = reactive({
  menu_id: null,
  parent_menu_name: '',
  menu_icon: '',
  menu_name: '',
  menu_url: '',
  menu_state: 1
});
const editingRow = ref(null); // 用于存储当前正在编辑的行数据
// 搜索相关
const searchKeyword = ref('');
const selectedFilter = ref('');

// 获取数据
const fetchData = async () => {
  try {
    let url = `/api/Menu/GetMenus`;
    // if (searchKeyword.value || selectedFilter.value) {
    //   url += '?';
    //   if (searchKeyword.value) {
    //     url += `keyword=${searchKeyword.value}&`;
    //   }
    //   if (selectedFilter.value) {
    //     url += `status=${selectedFilter.value}`;
    //   }
    // }
    const res = await axios.get(url);
    tableData.value = res.data;
  } catch (error) {
    console.error('Error fetching tableData:', error);
    ElMessage.error('数据获取失败');
  }
};

// 查找上级菜单名称
const findParentMenuName = async (menu_pid) => {
  try {
    const response = await axios.get(`/api/Menu/GetMenuName?Menu_pid=${menu_pid}`);
    return response.menu_name || '';
  } catch (error) {
    console.error('获取上级菜单名称失败:', error);
    return '';
  }
};

// 打开对话框
const openDialog = async (row) => {
  console.log(row)
  dialogVisible.value = true;
  editingRow.value = row;
  if (row) {
    dialogTitle.value = '编辑菜单';
    const parentMenuName = await findParentMenuName(row.menu_pid);
    Object.assign(formData, {
      ...row,
      parent_menu_name: parentMenuName
    });
  } else {
    dialogTitle.value = '新增菜单';
    Object.assign(formData, {
      menu_id: null,
      parent_menu_name: '',
      menu_icon: '',
      menu_name: '',
      menu_url: '',
      menu_state: 1
    });
  }
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
  editingRow.value = null;
};

// 提交表单
const submitForm = async () => {
  try {
    if (editingRow.value) {
      await axios.put(`/api/Menu/UpdateMenu/${editingRow.value.menu_id}`, formData);
      ElMessage.success('更新成功');
    } else {
      await axios.post('/api/Menu/CreateMenu', formData);
      ElMessage.success('新增成功');
    }
    closeDialog();
    fetchData(); // 重新加载数据
  } catch (error) {
    console.error('Error submitting form:', error);
    ElMessage.error('操作失败');
  }
};

// 导入数据
const importData = () => {
  // 导入逻辑
  ElMessage.info('导入功能待实现');
};

// 打开编辑对话框
const openEditDialog = () => {
  const selectedRows = tableData.value.filter(item => item.selected);
  if (selectedRows.length === 1) {
    openDialog(selectedRows[0]);
  } else {
    ElMessage.warning('请选择一条记录进行编辑');
  }
};

// 新增子菜单
const addSubMenu = (row) => {
  dialogVisible.value = true;
  dialogTitle.value = '新增子菜单';
  Object.assign(formData, {
    menu_id: null,
    parent_menu_name: row.menu_name,
    menu_icon: '',
    menu_name: '',
    menu_url: '',
    menu_state: 1
  });
  editingRow.value = null;
};

// 查询
const query = () => {
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = '';
  selectedFilter.value = '';
  fetchData();
};

// 删除菜单
const deleteMenu = (row) => {
  ElMessageBox.confirm('确定删除该记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      axios
        .delete(`/api/Menu/DeleteMenu/${row.menu_id}`)
        .then(() => {
          ElMessage.success('删除成功!');
          fetchData(); // 重新加载数据
        })
        .catch(() => {
          ElMessage.error('删除失败');
        });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除'
      });
    });
};

// 初始数据获取
onMounted(fetchData);
</script>

<style scoped>
.container {
  display: flex;
  gap: 20px;
  height: 100%;
  width: 97%;
}

.main {
  width: 80%;
  flex: 1;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.el-table {
  height: 90%;
}
</style>